package per.jdz.circuitbreaker.proxy;

import java.lang.reflect.Field;
import java.util.Set;

import org.springframework.cglib.proxy.Enhancer;

import per.jdz.circuitbreaker.ICircuitBreakerController;

public class CircuitBreakerProxyFactory {
    
    public static <T> T getProxy(Object bean, Set<Integer> methods, ICircuitBreakerController circuitBreakerController)
            throws NoSuchFieldException, IllegalAccessException {
        final Class<?> aClass = bean.getClass();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(aClass);
        enhancer.setCallback(new CircuitBreakerProxy(bean, methods, circuitBreakerController));
        final T t = (T) enhancer.create();
        // 将原始对象的字段值复制到代理对象上
        copyBeanProperties(bean, t);
        return t;
    }

    private static void copyBeanProperties(Object source, Object target) {
        try {
            // 获取源对象的所有字段,包括非 public 字段
            Field[] fields = source.getClass().getDeclaredFields();
            for (Field field : fields) {
                // 设置可访问性,以便我们可以访问 private 字段
                field.setAccessible(true);
                // 将字段值从源对象复制到目标对象
                field.set(target, field.get(source));
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to copy bean properties", e);
        }
    }
}
